﻿/// <reference path="jquery-1.4.4.min.js" />

/// <reference path="markerclusterer_packed.js" />

/// <reference path="markermanager_packed.js" />

var wm = wm || {};
wm.map = {
	icon: "",
	zoom: 10,
	smallIconZoom: 13,
	houseInfoTpl:
        '<table width="190" border="0">'
        + '  <tr>'
        + '    <td width="92" rowspan="5"><a href="/r/i/{uuid}.html"><img style="border: 1px solid #DDD;padding: 3px;" name="" src="/r/p/90/120/{pic_main}" width="90" height="120" alt="" /></a></td>'
        + '    <td width="78" class="lan">{place}</td>'
        + '  </tr>'
        + '  <tr>'
        + '    <td>{district}</td>'
        + '  </tr>'
        + '  <tr>'
        + '    <td>{layout} {size}㎡</td>'
        + '  </tr>'
        + '  <tr>'
        + '    <td class="red">{fee_min}</td>'
        + '  </tr>'
        + '</table>',
	//'<div class="lajl_1">'
	//+'	<ul class="img">'
	//+'		<li>'
	//+'			<a href="/r/i/{uuid}.html"> '
	//+'				<img src="/r/p/90/120/{pic_main}" alt="">'
	//+'			</a>'
	//+'		</li>'
	//+'	</ul>'
	//+'	<ul class="text">'
	//+'	<li class="lan">{place}</li>'
	//+'	<li>{district}</li>'
	//+'	<li>'
	//+'		{layout}'
	//+'		{size}㎡ '
	//+'	</li>'
	//+'	<li class="red">{fee_min}</li>'
	//+'	</ul>'
	//+'</div>' ,
	//"<img src='/r/p/120/90/{pic_main}'/><br/>Name:{name},Address:{address}<br/>la:{latitude},lo:{longtitude}",
	loadDelay: 1000,
	defaultCenter: { latitude: 35.41, longtitude: 139.44 }
};

jQuery.fn.extend({
	//地图检索控件
	gmap: function (options)
	{
		var defaultOptions = {
			zoom: wm.map.zoom,
			//默认起始坐标
			center: wm.map.defaultCenter,
			railroad: false,
			paramsForm: $("form")
		};
		jQuery.extend(defaultOptions, options);

		var reloadData = function (map)
		{
			var params = map.params || {};
			var locationParam = {
				fn_max_longtitude: 0,
				fn_max_latitude: 0,
				fn_min_longtitude: 0,
				fn_min_latitude: 0,
				fp_json: true
			};
			var b = map.getBounds();
			var ne = b.getNorthEast();
			var sw = b.getSouthWest();
			locationParam.fn_max_longtitude = ne.lng();
			locationParam.fn_max_latitude = ne.lat();
			locationParam.fn_min_longtitude = sw.lng();
			locationParam.fn_min_latitude = sw.lat();

			jQuery.extend(params, locationParam);

			if (defaultOptions.paramsForm)
				jQuery.extend(params, defaultOptions.paramsForm.serializeObject());



			//debug
			$("#showParam").text(params.fn_max_longtitude + "-" + params.fn_max_latitude + "-" + params.fn_min_longtitude + "-" + params.fn_min_latitude);

			if (map.timeout)
			{
				clearTimeout(map.timeout);
			}

			map.timeout = setTimeout(function () { $.post("/r/search.html", params, showHouses); clearTimeout(map.timeout); }, wm.map.loadDelay);



			function showHouses(result)
			{
				if (result.item == undefined || result.item.length == 0)
					return;
				for (var i = 0; i < result.item.length; i++)
				{
					var house = result.item[i];

					if (shouldAdd(map, house) == false)
						continue;

					var p = new google.maps.LatLng(house.latitude, house.longtitude);
					var marker = new google.maps.Marker({
						position: p,
						title: house.name,
						house: house
					});
					var content = wm.map.houseInfoTpl;
					content = content.replace("{fee_min}", (house.room.total_fee_min || "") + lt.price_start);
					content = content.replace("{uuid}", house.room.uuid);
					content = content.replace("{pic_main}", house.pic_main);
					content = content.replace("{place}", house.placename || "");
					content = content.replace("{district}", house.districtname || "");
					content = content.replace("{layout}", house.layout.name || "");
					content = content.replace("{size}", house.room.space ? house.room.space.toFixed(2) : '');
					bindMarkerDetails(map, marker, content);
				}
			}
		};

		//判断是否需要添加Marker
		function shouldAdd(map, house)
		{
			if (map.houses == undefined)
				map.houses = [];
			var exist = false;
			var house_key = house.room.uuid; //house.latitude + "-" + house.longtitude;
			for (var j = 0; j < map.houses.length; j++)
			{
				if (map.houses[j] == house_key)
				{
					exist = true;
					break;
				}
			}
			if (exist)
				return false;
			map.houses[map.houses.length] = house_key;
			return true;
		}

		function clearMarkers(map)
		{
			map.houses = [];
			if (map.markerCluster)
				map.markerCluster.clearMarkers();
		}


		function bindMarkerDetails(map, marker, content)
		{
			if (map.markerCluster == undefined)
				map.markerCluster = new MarkerClusterer(map, [], { maxZoom: 14 });
			map.markerCluster.addMarker(marker);
			map.infoWindows = map.infoWindows || [];
			var infowindow = new google.maps.InfoWindow({
				content: content
			});

			map.infoWindows.push(infowindow);

			google.maps.event.addListener(marker, 'click', function ()
			{
				for (var i = 0; i < map.infoWindows.length; i++)
				{
					map.infoWindows[i].close();
				}
				infowindow.open(map, marker);
			});
		}

		//跳转到指定地区
		this.goto = function (address)
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				geocoder = new google.maps.Geocoder();
				geocoder.geocode({ address: "日本," + address, region: 'jp', language: "ja_JP" }, function (results, status)
				{
					if (status == google.maps.GeocoderStatus.OK)
					{
						map.fitBounds(results[0].geometry.viewport);
					} else
					{
						alert(lt.nosuchaddress + address);
					}
				});
			});
		}
		this.setZoom = function (zoom)
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				map.setZoom(zoom);
			});
		}
		this.reload = function ()
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				clearMarkers(map);
				reloadData(map);
			});
		}
		this.setParams = function (data)
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				map.params = data;
				clearMarkers(map);
				reloadData(map);
			});
		}
		this.addParams = function (data)
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				map.params = jQuery.extend(map.params, data);
				clearMarkers(map);
				reloadData(map);
			});
		}
		this.railline = function ()
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				//map.setMapTypeId(lt.line);
			});

		}
		this.road = function ()
		{
			return this.each(function ()
			{
				var map = $(this).data("map");
				//map.setMapTypeId(ROADMAP);
			});
		}

		this.each(function (index, el)
		{
			var it = $(el);
			if (it.data("map"))
				return;
			var latlng = new google.maps.LatLng(it.attr("latitude") || wm.map.defaultCenter.latitude, it.attr("longtitude") || wm.map.defaultCenter.longtitude);
			var myOptions = {
				zoom: defaultOptions.zoom,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			if (defaultOptions.railroad)
			{
				myOptions.mapTypeControlOptions = { mapTypeIds: [lt.linemap, google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID] };
			}

			var map = new google.maps.Map(el, myOptions);

			$("#loading").ajaxStart(function ()
			{
				var p = it.position();
				$(this).css("position", "absolute").css({ top: p.top + it.height() / 2, left: p.left + it.width() / 2 }).show();
			});
			$("#loading").ajaxStop(function ()
			{
				$(this).hide();
			});
			it.data("map", map);

			if (defaultOptions.railroad)
			{
				var railStyle = [
				{
					featureType: "transit.line",
					elementType: "geometry",
					stylers: [{
						hue: "#005500"
					}, {
						saturation: 0
					}]
				},
				 {
				 	featureType: "transit.station.airport",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "transit.station.bus",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "road",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.school",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.government",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.sports_complex",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.medical",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.attraction",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.business",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.medical",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "poi.place_of_worship",
				 	stylers: [
						{ visibility: "off" }
					]
				 },
				 {
				 	featureType: "landscape",
				 	stylers: [
						{ visibility: "off" }
					]
				 }];
				var railMapType = new google.maps.StyledMapType(railStyle, {
					name: lt.linemap
				});

				map.mapTypes.set(lt.linemap, railMapType);
				//map.setMapTypeId('rail');
			}

			google.maps.event.addListener(map, 'zoom_changed', function ()
			{
				reloadData(map);
			});
			google.maps.event.addListener(map, 'bounds_changed', function ()
			{
				reloadData(map);
			});
		});

		return this;
	},
	//显示一个房屋的位置
	gmapDisplay: function ()
	{
		return this.each(function (index, el)
		{
			var it = $(el);
			var latlng = new google.maps.LatLng(it.attr("latitude") || defaultOptions.center.latitude, it.attr("longtitude") || defaultOptions.center.longtitude);
			var myOptions = {
				zoom: 14,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(el, myOptions);
			var marker = new google.maps.Marker({
				position: latlng,
				map: map
			});
		})
	}
});
